#include "Buffer.h"
#include <cstring>

Buffer::Buffer(uint16_t sep) : M_SEP(sep)
{
}
Buffer::~Buffer()
{
}

void Buffer::append(const char *data, size_t size)
{
    m_buf.append(data, size);
}

void Buffer::append_by_sep(const char *data, size_t size)
{
    //如果M_SEP为0，则直接追加数据
    if(M_SEP == 0)
    {
        m_buf.append(data, size);
    }
    //如果分隔符为1，则追加数据长度和数据
    else if( M_SEP == 1)
    {
        m_buf.append((char *)&size, 4);
        m_buf.append(data, size);
    }
    else if( M_SEP==2)
    {

    }

}

size_t Buffer::size()
{
    return m_buf.size();
}

const char *Buffer::data()
{
    return m_buf.data();
}

void Buffer::clear()
{
    m_buf.clear();
}

void Buffer::erase(size_t pos, size_t n)
{
    m_buf.erase(pos, n);
}

bool Buffer::pick_message(std::string& ss)
{
    if(m_buf.size()==0)
        return false;
    
    if(M_SEP ==0)
    {
        ss = m_buf;
        m_buf.clear();
    }
    else if (M_SEP ==1)
    {
        //解析报文
        int len = 0;
        memcpy(&len, m_buf.data(), 4);
        //没有读取到完整数据
        if (m_buf.size() < len + 4)
            return false;
        //读取到完整数据进行解析
        ss = m_buf.substr(4, len);
        m_buf.erase(0, len + 4); 
    }
    else if(M_SEP ==2)
    {

    }
    return true;
}